<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="cascaderValue" :options="cateLists" :props="cascaderProps" @change="cascaderHandleChange"></el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="tabActiveName" @tab-click="tabHandleClick">
        <!-- 动态 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtndisabled" @click="openAddDialog">添加参数</el-button>
          <el-table :data="manySortParams" style="width: 100%">
            <!-- 扩展行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable type="success" size="mini" @close="closeTag(scope.row,i)">{{item}}</el-tag>
                <!-- 添加新的标签按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="openEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" @click="openDeleteDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtndisabled" @click="openAddDialog">添加属性</el-button>
          <el-table :data="onlySortParams" style="width: 100%">
            <!-- 扩展行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable type="success" size="mini" @close="closeTag(scope.row,i)">{{item}}</el-tag>
                <!-- 添加新的标签按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="openEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" @click="openDeleteDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form ref="addFormref" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item :label="titleText" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog :title="'编辑'+titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form ref="editFormref" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateLists();
  },
  data() {
    return {
      //级联选择器选择的数据
      cascaderValue: [],
      //商品分类所有数据
      cateLists: [],
      //   props属性参数
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: 'hover'
        // checkStrictly: true,
      },
      // 选中选项卡的name
      tabActiveName: 'many',
      isBtndisabled: true,
      // 获取到的动态参数
      onlySortParams: [],
      // 获取到的静态参数
      manySortParams: [],
      addDialogVisible: false,
      addForm: {
        name: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    // 获取商品分类所有数据
    getCateLists() {
      this.$http.get("categories").then((res) => {
        this.cateLists = res.data.data;
      });
    },
    // 级联选择器选中后执行的函数
    cascaderHandleChange() {
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.onlySortParams = []
        this.manySortParams = []
        return this.$message.error('请选择第三级分类')
      }
      this.isBtndisabled = false
      this.$http.get(`categories/${this.cascaderValue[2]}/attributes`, { params: { sel: `${this.tabActiveName}` } }).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('参数获取失败')
        }
        res.data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        });
        console.log(res.data.data);
        this.$message.success('参数获取成功')
        if (this.tabActiveName == 'many') {
          this.manySortParams = res.data.data
        } else {
          this.onlySortParams = res.data.data
        }
      })

    },
    // tab 被选中时触发
    tabHandleClick() {
      this.cascaderHandleChange()
    },
    // 打开添加对话框
    openAddDialog() {
      this.addDialogVisible = true
    },
    // 关闭对话框
    addDialogClosed() {
      this.$refs.addFormref.resetFields()
    },
    // 提交添加参数
    addParams() {
      this.$refs.addFormref.validate(validate => {
        if (!validate) {
          return this.$message.error('表单预校验失败')
        }
        this.$http.post(`categories/${this.cascaderValue[2]}/attributes`, { attr_name: this.addForm.name, attr_sel: this.tabActiveName }).then(res => {
          if (res.data.meta.status !== 201) {
            return this.$message.error('添加失败')
          }
          this.addDialogVisible = false
          this.cascaderHandleChange()
          this.$message.success('添加成功')
        })
      })
    },
    // 打开编辑对话框
    openEditDialog(attrId) {
      this.$http.get(`categories/${this.cascaderValue[2]}/attributes/${attrId}`, { params: { attr_sel: this.tabActiveName } }).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('获取参数信息失败！')
        }
        this.editForm = res.data.data
        this.editDialogVisible = true
      })
    },
    editDialogClosed() {
      this.$refs.editFormref.resetFields()
    },
    // 提交编辑参数
    editParams() {
      this.$refs.editFormref.validate(validate => {
        if (!validate) {
          return this.$message.error('表单预校验失败')
        }
        this.$http.put(`categories/${this.cascaderValue[2]}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.tabActiveName }).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('编辑失败')
          }
          this.editDialogVisible = false
          this.cascaderHandleChange()
          this.$message.success('编辑成功')
        })
      })
      this.editDialogVisible = false
    },
    // 删除参数询问弹窗
    openDeleteDialog(attr_id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`categories/${this.cascaderValue[2]}/attributes/${attr_id}`).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.cascaderHandleChange()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 新的标签按钮显示input
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 新的标签文本框回车跟光标
    async handleInputConfirm(row) {
      // 判断输入框存储文本是否为空 空的话不执行,防止输入框失去焦点跟回车事件冲突
      if (!row.inputValue) return
      const { data: res } = await this.$http.put(`categories/${this.cascaderValue[2]}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(" ") + ' ' + row.inputValue,
      })
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('添加失败')
      }
      // 给当前页面扩展行添加数据直接渲染,这样就不用重新获取服务器中的attr_vals再次渲染
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      this.$message.success('添加成功')
    },
    async closeTag(row, i) {
      row.attr_vals.splice(i, 1)
      console.log(row.attr_vals, 'row.attr_vals');
      const { data: res } = await this.$http.put(`categories/${this.cascaderValue[2]}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(" ")
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数属性值失败')
      }
      this.$message.success('修改参数属性值成功')
    }
  },
  computed: {
    // 对话框标题
    titleText() {
      if (this.tabActiveName == "many") {
        return "动态参数"
      }
      return "静态属性"
    },
  }
};
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>